<template>
  <div>
    <el-drawer
      :visible.sync="drawerShow"
      :title="title"
      :destroy-on-close="true"
      custom-class="wxkj-drawer"
      size="500px"
    >
      <div v-if="drawerShow" class="drawer-content">
        <el-form ref="form" :model="form" :rules="rules" class="pl10 pr10" label-width="110px">
          <h2 class="f16 form-title">企业HR信息</h2>
          <el-form-item v-show="false" label="id：" prop="id">
            <el-input v-model="form.id" />
          </el-form-item>
          <el-form-item label="联系人" prop="name">
            <el-input v-model="form.name" placeholder="请填写联系人" />
          </el-form-item>
          <el-form-item label="联系人手机号" prop="mobile">
            <el-input v-model="form.mobile" placeholder="请准确填写手机号" />
          </el-form-item>
          <el-form-item label="联系人邮箱" prop="mobile">
            <el-input v-model="form.enMail" placeholder="请准确填写邮箱" />
          </el-form-item>
          <el-form-item label="称呼" prop="callName">
            <el-input v-model="form.callName" placeholder="请填写您的称呼，用于向求职者展示" />
          </el-form-item>
          <!-- 客户要求隐藏
       <el-form-item label="身份证号" prop="idNumber">
         <el-input v-model="form.idNumber" placeholder="请填写您的身份证号" />
       </el-form-item>

      <el-form-item label="身份证国徽面" prop="positiveFileid">
        <div class="fl upload-wrap">
          <el-upload
            ref="idCard1"
            accept=".jpg,.png,.jpeg"
            class="uploader-item"
            :action="$uploadUrl"
            :data="{'biz':'private/ent/' + new Date().getFullYear() + '/' + parseInt(new Date().getMonth() + 1)}"
            :headers="{'X-Access-Token':token}"
            :show-file-list="false"
            :limit="1"
            :on-success="idCardUpload_positiveFile"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="positiveFile" :src="positiveFile" class="avatar">
            <i v-else class="el-icon-plus uploader-item-icon" />
          </el-upload>
        </div>
      </el-form-item>
      <el-form-item label="身份证人像面" prop="backFileid">
        <div class="fl upload-wrap">
          <el-upload
            ref="idCard2"
            accept=".jpg,.png,.jpeg"
            class="uploader-item"
            :action="$uploadUrl"
            :data="{'biz':'private/ent/' + new Date().getFullYear() + '/' + parseInt(new Date().getMonth() + 1)}"
            :headers="{'X-Access-Token':token}"
            :show-file-list="false"
            :limit="1"
            :on-success="idCardUpload_backFile"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="backFile" :src="backFile" class="avatar">
            <i v-else class="el-icon-plus uploader-item-icon" />
          </el-upload>
        </div>
      </el-form-item>
      -->
          <h2 class="f16 form-title">企业基本信息</h2>
          <el-form-item label="企业LOGO" prop="enLogo">
            <div class="logo-wrap">
              <!-- <el-upload
               ref="logo"
               accept=".jpg,.png,.jpeg"
               class="uploader-item"
               :action="$uploadUrl"
               :data="{'biz':'public/ent/' + new Date().getFullYear() + '/' + parseInt(new Date().getMonth() + 1)}"
               :headers="{'X-Access-Token':token}"
               :show-file-list="false"
               :on-success="logoUpload"
               :before-upload="beforeAvatarUpload"
               :limit="1"
             >
               <img v-if="enLogo" :src="enLogo" class="avatar">
               <i v-else class="el-icon-plus uploader-item-icon" />
             </el-upload> -->
              <upload-cropper
                ref="uploadCropper"
                class="wrap"
                :return-obj="true"
                :enlarge="2"
                :init-img="enLogo"
                :tip-content="'只支持JPG格式,建议使用大小不要超过1000k、350*150像素的图片'"
                :fixed-number="[350,150]"
                @upload="getUploadImgId"
              />
            </div>
          </el-form-item>
          <el-form-item label="企业名称" prop="enName">
            <el-input v-model="form.enName" placeholder="请输入企业名称,需与企业证件保持一致" />
          </el-form-item>
          <el-form-item label="所属专场：">
            <el-select v-model="form.affUnit" clearable placeholder="请选择">
              <el-option
                v-for="item in deptOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="企业所在地" prop="enAddress">
            <el-cascader ref="areaSelect" v-model="form.enAddress" :options="areaData" style="width: 100%;" @change="chooseAddress('areaSelect')" />
          </el-form-item>
          <!-- 20240416 fangsong   因高德地图API收费，去掉所有关于地图的东西  -->
          <!--           <el-form-item label="详细地址" prop="enLocation">
              <el-row>
                <el-col :span="20">
                  <el-input v-model="form.enLocation" :disabled="!form.lng||!form.enLocation" />
                </el-col>
                <el-col :span="4">
                  <el-button
                    class="fr"
                    icon="el-icon-location"
                    @click="graspLongLat"
                  />
                </el-col>
              </el-row>
            </el-form-item>-->
          <el-form-item label="详细地址" prop="enLocation">
            <el-input v-model="form.enLocation" placeholder="请准确填写详细地址" />
          </el-form-item>
          <el-form-item label="所属行业" prop="enTrade">
            <el-cascader v-model="form.enTrade" :options="tradeData" style="width: 100%;" />
          </el-form-item>
          <el-form-item label="企业性质" prop="enNature">
            <el-select v-model="form.enNature" clearable style="width: 100%;" placeholder="请选择">
              <el-option v-for="(item,index) in enNature" :key="index" :label="item" :value="item" />
            </el-select>
          </el-form-item>
          <el-form-item label="对公账号" prop="account">
            <el-input v-model="form.account" placeholder="请填写对公账号" />
          </el-form-item>
          <el-form-item label="开户行全称" prop="bankName">
            <el-input v-model="form.bankName" placeholder="请输入开户行全称,例:中国工商银行股份有限公司北京德外支行" />
          </el-form-item>
          <el-form-item label="上传营业执照" prop="license">
            <div class="upload-wrap">
              <el-upload
                ref="uploadLicense"
                accept=".jpg,.png,.jpeg"
                :class="[form.license.split(',').length>=5?'hidBtn':'']"
                list-type="picture-card"
                :action="$uploadUrl"
                :data="{'biz':'private/ent/' + new Date().getFullYear() + '/' + parseInt(new Date().getMonth() + 1)}"
                :headers="{'X-Access-Token':token}"
                :on-success="licenseSuccess"
                :on-remove="licenseRemove"
                :limit="5"
                :file-list="fileList"
                :multiple="true"
              >
                <i class="el-icon-plus uploader-item-icon" />
              </el-upload>
              <p class="tips">请上传营业执照照片({{ form.license?form.license.split(',').length:0 }}/5)<span class="el-link el-button--text ml10" @click="tipsdialogShow">查看上传示例</span></p>
            </div>
          </el-form-item>
          <div class="drawer-form-buttom-group">
            <el-button type="primary" :loading="waiting" @click="onSubmit('form')">{{ form.id?'保存':'立即创建' }}</el-button>
            <el-button @click="drawerShow = false">取消</el-button>
          </div>
        </el-form>
      </div>
    </el-drawer>
    <el-dialog :visible.sync="tipsdialogVisible" width="360px">
      <el-image
        style="width: 320px; height: 220px"
        :src="require('@/assets/images/business-license.png')"
        :preview-src-list="[require('@/assets/images/business-license.png')]"
      />
      <!-- <img src="../../../assets/images/business-license.png"> -->
      <div class="tips-content">
        <p>注意事项</p>
        <p>1.企业名称与企业证件信息必须一致；</p>
        <p>2.营业执照有效期大于15天；</p>
        <p>3.营业执照政府章与工商局登记机关信息一致；</p>
        <p>4.复印版证照需加盖企业红色公章，签章需清晰可见；</p>
        <p>5.证件完整，清晰，有效，不能为电子版或截屏。</p>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="tipsdialogVisible = false">确 定</el-button>
      </div>
    </el-dialog>
    <!--    <map-dialog ref="map" @returnInfo="getMapInfo" />-->
  </div>
</template>

<script>
import { mapState } from 'vuex'
import uploadCropper from '@/components/uploadCropper'
// import store from '@/store'
// import mapDialog from '@/components/CurriculumVitaeEditDrawer/components/mapDialog'
import { sign } from '@/api/common'
import { companyAdd, companyView, companyEdit } from '@/api/vip-company'
export default {
  components: {
    /* mapDialog,*/
    uploadCropper
  },
  data() {
    // 身份证号校验
    var idCardValidate = (rule, value, callback) => {
      if (value == '') { // 不填写不验证
        callback()
      }
      var reg = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/
      if (!reg.test(value)) {
      	callback(new Error('请填写正确的身份证号'))
      }
      callback()
    }
    var mobileValidate = (rule, value, callback) => {
      if (!(/^1\d{10}$/.test(value))) {
      	callback(new Error('请准确填写手机号'))
      }
      callback()
    }
    return {
      deptOptions: [
        { label: '无', value: '0' },
        { label: '河南省工信厅', value: 'gxt' }
      ],
      drawerShow: false,
      title: '',
      citys: {
        lazy: true,
        lazyLoad(node, resolve) {
          const { level } = node
          setTimeout(() => {
            const nodes = Array.from({ length: level + 1 })
              .map(item => ({
                value: ++id,
                label: `选项${id}`,
                leaf: level >= 2
              }))
              // 通过调用resolve将子节点数据返回，通知组件数据加载完成
            resolve(nodes)
          }, 1000)
        }
      },
      form: {
        id: '',
        name: '',
        mobile: '',
        enMail: '',
        email: '', // 查询方法里面返回的是 enMail，保存时，确是email
        callName: '',
        idNumber: '',
        positiveFileid: '',
        backFileid: '',
        enLogo: '',
        enName: '',
        enAddress: [],
        lat: 0,
        lng: 0,
        enLocation: '',
        enTrade: [],
        enNature: '',
        account: '',
        bankName: '',
        license: '',
        affUnit: ''
      },
      positiveFile: '', // 正面照
      backFile: '', // 反面照
      enLogo: '', // logo
      license: '', // 营业执照
      imageUrl: '',
      rules: {
        name: [
          { required: true, message: '请填写联系人', trigger: 'blur' },
          { min: 2, max: 5, message: '长度在 2 到 5 个字符', trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请准确填写手机号', trigger: 'blur' },
          { validator: mobileValidate, trigger: 'blur' }
        ],
        enMail: [
          { required: true, message: '请准确填写邮箱', trigger: 'blur' },
          { type: 'email', message: '请填写正确的邮箱', trigger: 'blur' }
        ],
        // callName: [
        //   { required: true, message: '请填写您的称呼，用于向求职者展示', trigger: 'blur' }
        // ],
        idNumber: [
          // { required: true, message: '请填写您的身份证号', trigger: 'blur' },
          { validator: idCardValidate, trigger: 'blur' }
        ],
        // positiveFileid: [
        //   { required: true, message: '请上传身份证正面照片' }
        // ],
        // backFileid: [
        //   { required: true, message: '请上传身份证反面照片' }
        // ],
        enLogo: [
          { required: true, message: '请上传企业LOGO' }
        ],
        enName: [
          { required: true, message: '请填写企业名称', trigger: 'blur' }
        ],
        enAddress: [
          { required: true, message: '请选择企业所在地' }
        ],
        enLocation: [
          { required: true, message: '请填写企业详细地址' }
        ],
        enTrade: [
          { required: true, message: '请选择所属行业' }
        ],
        enNature: [
          { required: true, message: '请选择企业性质' }
        ],
        license: [
          { required: true, message: '请上传营业执照' }
        ]
      },
      dialogImageUrl: '',
      tipsdialogVisible: false, // 营业执照弹窗
      fileList: [],
      points: null,
      waiting: false
      // areaData: [],
      // tradeData: []
    }
  },
  watch: {
    drawerShow(bl) {
      if (!bl) {
        this.$refs.form.resetFields()
        this.fileList = []
        this.positiveFile = '' // 清空图片
        this.backFile = ''// 清空图片
        this.enLogo = ''// 清空图片
        this.license = ''// 清空图片
        this.$refs['idCard1'].clearFiles()// 清空上传列表
        this.$refs['idCard2'].clearFiles()// 清空上传列表
        this.$refs['logo'].clearFiles()// 清空上传列表
        this.$refs['uploadLicense'].clearFiles()// 清空上传列表
      }
    }
  },
  computed: {
    ...mapState({
      token: state => state.user.token,
      enNature: state => state.app.enNature,
      areaData: state => state.app.areaData,
      tradeData: state => state.app.tradeData
    })
  },
  async created() {
    // 城市数据
    // if (this.$store.state.app.areaData.length === 0) {
    //   const res = await store.dispatch('app/getArea', 'area')
    //   this.areaData = res.result
    // } else {
    //   this.areaData = this.$store.state.app.areaData
    // }
    // // 行业数据
    // if (this.$store.state.app.tradeData.length === 0) {
    //   const res = await store.dispatch('app/getTrade', 'industry')
    //   this.tradeData = res.result
    // } else {
    //   this.tradeData = this.$store.state.app.tradeData
    // }
  },
  methods: {
    getUploadImgId(e) {
      this.$refs.form.clearValidate('enLogo')
      this.form.enLogo = e.fileId
    },
    show(title, rowData) {
      this.title = title
      this.drawerShow = true
      if (rowData) {
        companyView({ id: rowData.id }).then(response => {
          var dataBody = response.result
          for (var k in this.form) {
            if (dataBody[k]) {
              this.form[k] = dataBody[k]
            }
          }
          this.form.enAddress = this.form.enAddress.split(',')
          this.form.enTrade = this.form.enTrade.split(',')
          this.enLogo = dataBody.enLogo_dictText
          if (dataBody.lat && dataBody.lng) {
            this.points = { center: [dataBody.lng, dataBody.lat], label: dataBody.city_dictText }
          }

          // 身份证国徽
          console.log('身份证国徽', dataBody.positiveFileid)
          if (dataBody.positiveFileid == '' || dataBody.positiveFileid == null) {
            this.positiveFile = ''
          } else {
            sign({ fileId: dataBody.positiveFileid }).then(res => {
              this.positiveFile = dataBody.positiveFileid_dictText + '?sign=' + res.result
            })
          }

          // 身份证人像
          if (dataBody.backFileid == '' || dataBody.backFileid == null) {
            this.backFile = ''
          } else {
            sign({ fileId: dataBody.backFileid }).then(res => {
              this.backFile = dataBody.backFileid_dictText + '?sign=' + res.result
            })
          }

          const ls = dataBody.license.split(',')
          const lds = dataBody.license_dictText.split(',')
          this.fileList = []
          // 营业执照
          ls.forEach((item, index) => {
            sign({ fileId: item }).then(res => {
              const obj = new Object()
              obj.url = lds[index] + '?sign=' + res.result
              obj.fileId = item
              this.fileList.push(obj)
            })
          })
        })
      }
    },
    onSubmit(formName) {
      // 清除校验图片 首先需判断图片是否上传再清除
      // this.$refs[formName].clearValidate()
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.waiting = true
          const parms = JSON.parse(JSON.stringify(this.form))
          const enAddress = JSON.parse(JSON.stringify(this.form)).enAddress
          parms.enTrade = parms.enTrade.join(',')
          parms.enAddress = enAddress.join(',')
          parms.province = enAddress[0]
          parms.city = enAddress[1]
          parms.email = parms.enMail// 查询用了enMail，保存确用 email
          if (this.form.id) {
            companyEdit(parms).then(res => {
              console.log(res)
              this.$message({
                type: 'success',
                message: '保存成功！'
              })
              this.drawerShow = false
              this.waiting = false
              this.$emit('refresh')
            }).catch(() => {
              this.waiting = false
            })
          } else {
            companyAdd(parms).then(res => {
              this.$message({
                type: 'success',
                message: '添加成功！'
              })
              this.waiting = false
              this.drawerShow = false
              this.$emit('refresh')
            }).catch(() => {
              this.waiting = false
            })
          }
        }
      })
    },
    idCardUpload_positiveFile(res, file) {
      if (res.code == 200) {
        this.$refs.form.clearValidate('positiveFileid')
        this.form.positiveFileid = res.result.fileId
        this.positiveFile = URL.createObjectURL(file.raw)
        this.$refs['idCard1'].clearFiles()// 清空上传列表
      } else {
        this.$message.error('上传失败')
      }
    },
    idCardUpload_backFile(res, file) {
      if (res.code == 200) {
        this.$refs.form.clearValidate('backFileid')
        this.form.backFileid = res.result.fileId
        this.backFile = URL.createObjectURL(file.raw)
        this.$refs['idCard2'].clearFiles()// 清空上传列表
      } else {
        this.$message.error('上传失败')
      }
    },
    logoUpload(res, file) {
      if (res.code == 200) {
        this.$refs.form.clearValidate('enLogo')
        this.form.enLogo = res.result.fileId
        this.enLogo = URL.createObjectURL(file.raw)
        this.$refs['logo'].clearFiles()// 清空上传列表
      } else {
        this.$message.error('上传失败')
      }
    },
    licenseSuccess(res, file, fileList) {
      if (res.code == 200) {
        this.$refs.form.clearValidate('license')
        this.licenseRemove(file, fileList)
      } else {
        this.$message.error('上传失败')
      }
    },
    licenseRemove(file, fileList) {
      console.log(file, fileList)
      const licenses = []
      fileList.forEach(item => {
        if (item.response) {
          licenses.push(item.response.result.fileId)
        }
        if (item.fileId) {
          licenses.push(item.fileId)
        }
      })
      this.form.license = licenses.join(',')
    },
    beforeAvatarUpload(file) {
      const istu = file.type
      // const isLt2M = file.size / 1024 / 1024 < 2
      if (istu !== 'image/png' && istu !== 'image/jpeg') {
        this.$message.error('图片格式不正确!')
        return false
      }
      // if (!isLt2M) {
      //   this.$message.error('上传头像图片大小不能超过 2MB!')
      // }
      return istu
      // return isJPG && isLt2M
    },
    tipsdialogShow() {
      this.tipsdialogVisible = true
    },
    /* graspLongLat() {
      if (!this.points) {
        this.$message.error('请先选择企业所在地')
        return false
      }
      this.$refs.map.show(this.points)
    },
    getMapInfo(arr, address) {
      console.log(address)
      this.form.lng = arr[0]
      this.form.lat = arr[1]
      if (address) {
        this.form.enLocation = address
      }
      this.$refs.form.clearValidate('enLocation')
    },*/
    chooseAddress(e) {
      const pnode = this.$refs[e].getCheckedNodes()[0].parent.data
      this.points = { center: pnode.center, label: pnode.label }
    }
  }
}
</script>

<style lang="scss" scoped>
  .form-title{
    margin: 15px 0 25px 0;
  }
  .logo-wrap{
    ::v-deep .el-upload{
      width: 175px;
      height: 75px;
      line-height: 73px;
    }
  }
  .upload-wrap{
    .hidBtn{
      ::after{
        display: block;
        content: "";
        clear: both;
      }
      ::v-deep .el-upload--picture-card{
        display:none;   /* 上传按钮隐藏 */
      }
    }
    .el-upload-list--picture-card::after{
      display: block;
      content: "";
      clear: both;
    }
    ::v-deep .el-upload-list--picture-card .el-upload-list__item{
      width: 100px;
      height: 100px;
      float: left;
      line-height: 98px;
      position: relative;
      .el-progress-circle{
        display: none !important;
      }
    }
    .uploader-item{
      width: 100px;
      height: 100px;
    }
    ::v-deep .el-upload{
      width: 100px;
      height: 100px;
      border: 1px dashed #d9d9d9;
      cursor: pointer;
      line-height: 98px;
      position: relative;
      border-radius: 6px;
      background: none;
      .uploader-item-icon {
        display: block;
        font-size: 28px;
        color: #8c939d;
        width: 98px;
        height: 98px;
        line-height: 98px;
        text-align: center;
      }
    }
    .tips{
      margin: 0;
      margin-top: 10px;
      line-height: 24px;
    }
  }
  .avatar {
    width: 98px;
    height: 98px;
    display: block;
  }
</style>
